<?php
/**
 * @description 用户管理
 * @author 张鹏  zhangpeng@tvmining.com
 * @version 1.0
 * @date 2017-04-19
 * @copyright Copyright (c) 2008 Tvmining (http://www.tvmining.com)
 */
namespace App\Services\Common;

use App\Contracts\CommonContract;
use LRedis;
use Curl;

class Common implements CommonContract
{
    public function test()
    {
        dd(123);
    }

    /**
     * 并发请求方法 (返回数据key与原数组一致的)
     * @param array urlArray
     * @return array
     */
    public function concurrent($urlArray)
    {
        $results = [];
        $ch = curl_multi_init();
        $chArr = []; 
        foreach ($urlArray as $key => $url) {
            $chArr[$key] = curl_init($url);
            curl_setopt($chArr[$key], CURLOPT_URL, $url);
            curl_setopt($chArr[$key], CURLOPT_RETURNTRANSFER, true);
            curl_setopt($chArr[$key], CURLOPT_TIMEOUT, 5);
            curl_multi_add_handle($ch, $chArr[$key]);
        }unset($key, $url);
        $running = 0;
        do { 
            curl_multi_exec($ch, $running); 
        } while ($running > 0); 
        foreach ($urlArray as $key => $url) {
            $results[$key] = curl_multi_getcontent($chArr[$key]); 
            curl_multi_remove_handle($ch, $chArr[$key]); 
        } 
        curl_multi_close($ch); 
        return $results;
    }

    public function get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function logs($title, $msg)
    {
        $data = date('Y-m-d H:i:s', time()).'    '.$msg;
        file_put_contents(storage_path().'/logs/'.$title.'.log', $data.PHP_EOL, FILE_APPEND);
    }
}